<?php
/**
 * 通过 CModelManager查询到 表对应的 Model，在model中获取表结构，减少数据库查询
 */

class CMysqlSchemaExt extends CMysqlSchema{
	/**
	 * 首先尝试从表对应的 model 中查找 SHOW CREATE TABLE，若没有则走父类
	 * @see parent::findConstraints
	 */
	protected function findConstraints($table) {
		$model = CModelManager::get($table->name);
		if(!@ class_exists($model) || !@ method_exists($model, 'getCreateTable')) return parent::findConstraints($table);
		$row = $model::getCreateTable();
		
		$matches=array();
		$regexp='/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
		foreach($row as $sql)
		{
			if(preg_match_all($regexp,$sql,$matches,PREG_SET_ORDER))
				break;
		}
		
		$temp = array('keys'=>array(), 'fks'=>array());
		foreach($matches as $match)
		{
			$keys=array_map('trim',explode(',',str_replace(array('`','"'),'',$match[1])));
			$fks=array_map('trim',explode(',',str_replace(array('`','"'),'',$match[3])));
			
			$temp['keys'][] = $keys;
			$temp['fks'][] = $fks;
			foreach($keys as $k=>$name)
			{
				$table->foreignKeys[$name]=array(str_replace(array('`','"'),'',$match[2]),$fks[$k]);
				if(isset($table->columns[$name]))
					$table->columns[$name]->isForeignKey=true;
			}
		}
	}
	
	/**
	 * 首先尝试从表对应的 model 中查找 SHOW FULL COLUMNS，若没有则走父类
	 * @see parent::findColumns
	 */
	protected function findColumns($table) {
		$model = CModelManager::get($table->name);
		if(!@ class_exists($model) || !method_exists($model, 'getFullColumns'))  return parent::findColumns($table);
		$columns = $model::getFullColumns();
		
		foreach($columns as $column) {
			$c = $this->createColumn($column);
			$table->columns[$c->name]=$c;
			if($c->isPrimaryKey)
			{
				if($table->primaryKey===null)
					$table->primaryKey=$c->name;
				elseif(is_string($table->primaryKey))
					$table->primaryKey=array($table->primaryKey,$c->name);
				else
					$table->primaryKey[]=$c->name;
				if($c->autoIncrement)
					$table->sequenceName='';
			}
		}
		return true;
	}
	
}